#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
using namespace std;

const int N = 1e4 + 10, INF = 0x3f3f3f3f;

int n, m;
vector<pair<int, int>> g[N];
int del[N];
int rt, mxsiz, tot, siz[N];
int getrt(int x, int fa)
{
    siz[x] = 1;
    int tmp = 0;
    for (auto [y, _] : g[x]) {
        if (y == fa || del[y]) continue;
        siz[x] += getrt(y, x);
        tmp = max(tmp, siz[y]);
    }
    tmp = max(tmp, tot - siz[x]);
    if (tmp < mxsiz) mxsiz = tmp, rt = x;
    return siz[x];
}
void calc(int x){/*按照题目意思求对应问题部分，变量根据需要自行添加*/}
void dfs(int x)
{
    del[x] = 1;calc(x);
    for (auto [y, _] : g[x]) {
        if (del[y]) continue;
        mxsiz = INF;tot = siz[y];
        getrt(y, x); dfs(rt);
    }
}
void solve()
{
    //...
    mxsiz = INF; tot = n;
    getrt(1, 0);
    dfs(rt);
    //...
}

signed main()
{
    // ios::sync_with_stdio(0);
    // cin.tie(0);cout.tie(0);
#define ONLINE_JUDGE
#ifndef ONLINE_JUDGE
    std::istringstream in(R"()");
    std::cin.rdbuf(in.rdbuf());
#endif
    int T = 1;
    //cin>>T;
    for (int i = 1;i <= T;i++) {
        solve();
    }
}